<template>
  <div>
    <p>扫码签到中...</p>
  </div>
</template>

<script>
import {
  getSignStatus
} from "@/api/attendance/attendanceRecord";
import {addSign, getCourseSelectionStatus} from "@/api/attendance/sign";
export default {
  data() {
    return {
      courseRecordId: '',
      unCodeCourseRecordId: null,
    }
  },
  created() {
    this.courseRecordId = this.$route.query.courseRecordId;
    this.convertCourseRecordId();
    this.isSelected(); // 是该课程学生才可以签到
  },
  methods: {
    convertCourseRecordId() {
      const position = 6;
      // 找到 'i' 的位置
      const iIndex = this.courseRecordId.indexOf('i', position);
      // 提取 courseRecordId
      this.unCodeCourseRecordId = this.courseRecordId.slice(position, iIndex);
    },
    isSelected(){
      getCourseSelectionStatus(this.unCodeCourseRecordId).then(response => {
        if(response.data){ // 是选择本课程的学生
          // 进行签到
          this.isSign();
        } else {
          // 不是选择本课程的学生
          this.redirectSign();
        }
      });
    },
    isSign(){
      getSignStatus(this.unCodeCourseRecordId).then(response => {
        const signStatus = response.data;
        if(signStatus === undefined){
          // 调用签到
          this.sign(this.unCodeCourseRecordId);
        } else {
          this.redirectSign();
        }
      });
    },
    /** 签到 */
    sign(courseRecordId) {
      const signData = {
        courseRecordId: courseRecordId
      };
      // 调用 addSign 函数发起签到请求
      addSign(signData)
        .then(response => {
          // 请求成功的处理逻辑
          this.$modal.msgSuccess("签到成功");
          this.redirectSign(); // 签到后跳转到进行签到列表页面
        })
        .catch(error => {
          // 请求失败的处理逻辑
          this.$modal.msgError(error);
        });
    },
    redirectSign(){
      // 关闭当前 tabs
      this.$store.dispatch("tagsView/delView", this.$route);
      // 路由跳转
      this.$router.push({path: '/scanSign/sign'});
    }
  }
}
</script>
